package com.intelligentpension.kotlinbluetoothprint.activity

import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import com.hjq.toast.ToastUtils
import com.intelligentpension.kotlinbluetoothprint.R
import com.intelligentpension.kotlinbluetoothprint.service.BtService
import com.intelligentpension.kotlinbluetoothprint.utils.ConstantUtils
import com.orhanobut.logger.Logger
import com.permissionx.guolindev.PermissionX

class MainActivity : AppCompatActivity(), View.OnClickListener {
    private lateinit var mAdapter: BluetoothAdapter
    private lateinit var mSearchBluetooth: Button
    private lateinit var mPrintOne: Button
    private lateinit var mPrintMore: Button
    private lateinit var mPrintPicture: Button
    private lateinit var mAdaress: TextView
    private lateinit var mName: TextView
    private var device: BluetoothDevice? = null
    private var startActivityForResult: ActivityResultLauncher<Intent> =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            Logger.e("收到返回的信息了" + it.resultCode)
            if (it.resultCode === 10) {

                var intent = it.data
                var name = intent!!.getStringExtra("name")
                var address = intent.getStringExtra("address")
                mAdaress.text = address
                mName.text = name

                //根据地址获取连接
                device = mAdapter.getRemoteDevice(address)
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        PermissionX.init(this@MainActivity).permissions(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN
        ).onForwardToSettings { scope, deniedList ->
            scope.showForwardToSettingsDialog(
                deniedList,
                "You need to allow necessary permissions in Settings manually",
                "OK",
                "Cancel"
            )
        }.request { allGranted, _, deniedList ->
            if (allGranted) {
                Toast.makeText(this, "All permissions are granted", Toast.LENGTH_LONG).show()
            } else {
                Toast.makeText(
                    this, "These permissions are denied: $deniedList", Toast.LENGTH_LONG
                ).show()
            }
        }
        mAdapter = (getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter

        mAdaress = findViewById<TextView>(R.id.devices_address)
        mName = findViewById<TextView>(R.id.title_text)
        mSearchBluetooth = findViewById<Button>(R.id.search_bluetooth)
        mPrintOne = findViewById<Button>(R.id.print_one)
        mPrintMore = findViewById<Button>(R.id.print_more)
        mPrintPicture = findViewById<Button>(R.id.print_picture)
        mSearchBluetooth.setOnClickListener(this@MainActivity)
        mPrintOne.setOnClickListener(this@MainActivity)
        mPrintMore.setOnClickListener(this@MainActivity)
        mPrintPicture.setOnClickListener(this@MainActivity)

        initBluetooth()
    }

    //蓝牙打印不考虑低功耗
    private fun initBluetooth() {

        if (mAdapter == null) {
            ToastUtils.show("当前设备不支持蓝牙")
        } else {
            //如果蓝牙没有开启
            if (!mAdapter.isEnabled) {
                if (mAdapter.state == BluetoothAdapter.STATE_OFF) {
                    //只有sdk大于30的时候,才会需要这个权限
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                        if (ActivityCompat.checkSelfPermission(
                                this, Manifest.permission.BLUETOOTH_CONNECT
                            ) != PackageManager.PERMISSION_GRANTED
                        ) {
                            return
                        }
                    }
                    mAdapter.enable()
                } else {
                    mName.text = "蓝牙未打开"
                    return
                }
            }
        }
    }

    @SuppressLint("MissingPermission")
    override fun onClick(p0: View?) {
        when (p0?.id) {
            //搜索蓝牙
            R.id.search_bluetooth -> {
                Intent(this, BluetoothListActivity::class.java).apply {
                    startActivityForResult.launch(this)
                }
            }
            //打印一张
            R.id.print_one -> {

                if (device == null) {
                    ToastUtils.show("请先连接蓝牙")
                    return
                }
                if (device!!.bondState == BluetoothDevice.BOND_BONDED) {
                    ToastUtils.show("开启打印")
                    Intent(applicationContext, BtService::class.java).apply {
                        this.action = ConstantUtils.TEST_ACTION
                        this.putExtra(ConstantUtils.ADRESS,mAdaress.text.toString())
                        startService(this)
                    }

                } else {
                    ToastUtils.show("请先连接蓝牙")
                    return
                }

            }
            //打印多张
            R.id.print_more -> {

            }
            //打印照片
            R.id.print_picture -> {

            }
        }
    }
}